package com.yz.crm.weixin.service.impl;

/**
 * Created by DOVE on 2015/12/14.
 */

import com.yz.common.util.HttpClientUtil;
import com.yz.common.util.JsonUtils;

import com.yz.crm.weixin.model.token.AuthUserInfoJson;
import com.yz.crm.weixin.service.WechatUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取用户微信信息服务
 */
@Service
public class WechatUserServiceImpl implements WechatUserService {
    private static final Log log = LogFactory.getLog(WechatUserServiceImpl.class);
    @Override
    public AuthUserInfoJson loadWechatUserInfoByOpenId(String openId, String serviceUrl) {
        if(StringUtils.isEmpty(openId)){
            return null;
        }
        AuthUserInfoJson  authUserInfoJson = null;
        Map param = new HashMap();
        param.put("openId", openId);

        String authUserInfoJsonStr = HttpClientUtil.post(serviceUrl, param, null);

        if(StringUtils.isNotEmpty(authUserInfoJsonStr)){
            try {
                authUserInfoJson = JsonUtils.toObject(authUserInfoJsonStr, AuthUserInfoJson.class);
            }catch (Exception e){
                log.info("url:"+ serviceUrl + ",code:" + openId + ",authUserInfoJsonStr:" + authUserInfoJsonStr);
            }

        }
        return authUserInfoJson;
    }

    @Override
    public AuthUserInfoJson loadWechatUserInfoByCode(String code,String serviceUrl) {
        if(StringUtils.isEmpty(code)){
            return null;
        }
        AuthUserInfoJson  authUserInfoJson = null;
        Map param = new HashMap();
        param.put("code", code);

        String authUserInfoJsonStr = HttpClientUtil.post(serviceUrl, param, null);

        if(StringUtils.isNotEmpty(authUserInfoJsonStr)){
            try {
                authUserInfoJson = JsonUtils.toObject(authUserInfoJsonStr, AuthUserInfoJson.class);
            }catch (Exception e){
                log.info("url:"+ serviceUrl + ",code:" + code + ",authUserInfoJsonStr:" + authUserInfoJsonStr);
            }
        }
        return authUserInfoJson;
    }
}
